package edu.fiu.cis.nursing.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.ui.RootPanel;

import edu.fiu.cis.nursing.shared.UserToken;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Nursing implements EntryPoint {

	public static final String NURSING_COOKIE_NAME = "sid";

	private UserToken token;

	private final NursingServiceAsync nursingService = GWT
			.create(NursingService.class);

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {

		// clear everything
		RootPanel.get("login").clear();

		// get session cookie
		String sessionID = Cookies.getCookie(NURSING_COOKIE_NAME);

		if (sessionID != null) {
			//
			nursingService.validateCookie(sessionID,
					new DefaultAsyncCallback<UserToken>() {

						@Override
						public void onSuccess(UserToken result) {
							token = result;
							if (result == null) {
								Cookies.removeCookie(NURSING_COOKIE_NAME);
								performLoginFlow(true);
							} else {
								performInteractiveFlow();
							}
						}
					});
		} else {
			performLoginFlow(false);
		}
	}

	public void performLoginFlow(boolean expired) {
		LoginWindow lw = new LoginWindow(nursingService, this);
		RootPanel.get("login").add(lw);
	}

	public void performInteractiveFlow() {
		RootPanel.get("login").clear();

	}

}
